package xdu.lz.stage5_jucUtils.chapter1_countdownlatch;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created at 2019/10/18 0018 下午 3:50
 */
public class CDL_test1 {

    private static class SimpleRunnable implements Runnable{

        private final int[] data;
        private final int index;

        private SimpleRunnable(int[] data, int index) {
            this.data = data;
            this.index = index;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(random.nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if((data[index] & 1) ==0 ){
                data[index] = (data[index] << 1);
            }else {
                data[index] *= 10;
            }
            System.out.println(Thread.currentThread()+" finished");
        }
    }
    private static final Random random = new Random(System.currentTimeMillis());

    private static ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws InterruptedException {
        //1 read from db
        int []data = queryFromDB();
        //2 handler
        for (int i = 0; i < data.length; i++) {
            executor.execute(new SimpleRunnable(data,i));
        }
        //怎么保证2处理完在处理3？ 第一种，join，第二种，利用线程池的API，第三种countDownLatch
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.HOURS);
        //3 save
        System.out.println("all the work finished.");
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }

    private static int[] queryFromDB(){
        return new int[]{1,2,3,4,5,6,7,8,9,10};
    }

}
